<template>
  <div class="goods-detail-page">
    <!-- 加载状态 -->
    <el-skeleton v-if="loading" class="goods-skeleton">
      <template #template>
        <div class="skeleton-image"></div>
        <div class="skeleton-info">
          <div class="skeleton-title"></div>
          <div class="skeleton-stats"></div>
          <div class="skeleton-price"></div>
          <div class="skeleton-meta"></div>
          <div class="skeleton-actions"></div>
        </div>
      </template>
    </el-skeleton>

    <div v-else>
      <!-- 商品主图区域 -->
      <div class="image-container">
        <el-carousel v-if="product.images && product.images.length" height="400px">
          <el-carousel-item v-for="(img, idx) in product.images" :key="img.id || idx">
            <img
                :alt="`${product.name || '商品'}-主图${idx+1}`"
                :src="img.imageUrl"
                class="main-image"
                @error="e => e.target.src = 'https://picsum.photos/800/400'"
                @click="handleImageClick(img.imageUrl)"
            />
          </el-carousel-item>
        </el-carousel>
      </div>

      <!-- 商品基本信息区域 -->
      <div class="info-container">
        <h1 class="goods-title">{{ product.name || '未知商品' }}</h1>

        <!-- 统计信息 -->
        <div class="stats">
          <span>浏览 {{ product.viewCount || 0 }}</span>
          <span>点赞 {{ likeCount }}</span>
          <span>收藏 {{ product.favoriteCount || 0 }}</span>
        </div>

        <!-- 价格区域 -->
        <div class="price-box">
          <span class="price">¥{{ product.price ? product.price.toFixed(2) : '0.00' }}</span>
        </div>

        <!-- 卖家信息与元数据 -->
        <div class="meta-info">
          <p>商品描述：{{ product.description || '暂无描述' }}</p>
          <p>
            发货地：
            {{
              product.address && product.address.length
                  ? (() => {
                    const defaultAddr = product.address.find(addr => addr.isDefault === 1);
                    const fallbackAddr = defaultAddr || product.address.find(addr => addr.isDefault === 0);
                    return fallbackAddr
                        ? `${fallbackAddr.province || ''}${fallbackAddr.city || ''}${fallbackAddr.district || ''}${fallbackAddr.detail || ''}`
                        : '未知';
                  })()
                  : '未知'
            }}
          </p>
          <p>发货人:{{ product.address[0].consignee || '未知发货人' }}</p>
          <p class="seller-info">
            卖家：{{
              product.address && product.address.length
                  ? product.seller?.username || product.seller?.realname || '未知卖家'
                  : product.seller?.username || product.seller?.realname || '未知卖家'
            }}
            <el-button
                v-if="product.sellerId || product.seller?.id"
                :class="[isFollowed ? 'followed-btn' : 'follow-btn']"
                :icon="isFollowed ? 'UserFilled' : 'User'"
                style="padding: 0; margin-left: 10px"
                type="text"
                @click="handleFollowSeller"
            >
              {{ isFollowed ? '已关注' : '关注卖家' }}
            </el-button>
            <el-button
                icon="ChatDotRound"
                style="padding: 0; margin-left: 5px; color: #409eff"
                type="text"
                @click="goToChat"
            ></el-button>
          </p>
          <p>发布日期：{{ formatDate(product.createdAt) || '未知' }}</p>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button
              :class="[isLiked ? 'liked-btn' : '']"
              :icon="isLiked ? 'ThumbsUpFilled' : 'ThumbsUp'"
              plain
              type="primary"
              @click="handleLike"
          >
            {{ isLiked ? '已点赞' : '点赞' }}
          </el-button>
          <el-button
              :class="[isFavorite ? 'favorited-btn' : '']"
              :icon="isFavorite ? 'StarFilled' : 'Star'"
              plain
              type="primary"
              @click="handleFavorite"
          >
            {{ isFavorite ? '已收藏' : '收藏' }}
          </el-button>
          <el-button class="buy-button" type="primary" @click="handleAddToCart"
          >加入购物车
          </el-button>
          <el-button class="buy-button" type="primary" @click="handleBuyNow"
          >立即购买
          </el-button>
        </div>
      </div>

      <!-- 详情与评论标签页 -->
      <div class="tabs-container">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="商品详情" name="detail">
            <div class="detail-content">
              <!-- 只显示商品图片，不判断详情文本 -->
              <div class="detail-images-list">
                <h3 class="detail-images-title">商品图片</h3>
                <div class="images-container-full">
                  <img
                      v-for="(img, idx) in product.images"
                      :key="idx"
                      :alt="`${product.name || '商品'}-图片${idx+1}`"
                      :src="img.imageUrl || 'https://picsum.photos/600/400'"
                      class="detail-image-item"
                      @click="handleImageClick(img.imageUrl)"
                      @error="e => e.target.src = 'https://picsum.photos/600/400'"
                  />
                </div>
              </div>

              <!-- 无图片时显示空状态 -->
              <el-empty
                  v-if="!product.images || product.images.length === 0"
                  class="no-detail-empty"
                  description="暂无商品图片"
              ></el-empty>
            </div>
          </el-tab-pane>

          <!-- 评论区域 -->
          <el-tab-pane label="商品评论" name="comment">
            <div class="comment-content">
              <el-input
                  v-model="commentInput"
                  class="comment-input"
                  placeholder="请输入评论内容"
                  type="textarea"
                  :rows="3"
              ></el-input>
              <el-button class="submit-comment" type="primary" @click="submitComment">
                发表评论
              </el-button>

              <div class="comments-list">
                <div
                    v-for="(comment, index) in reviews"
                    :key="comment.id || index"
                    class="comment-item"
                >
                  <img
                      :alt="getUserName(comment)"
                      :src="getUserAvatar(comment)"
                      class="user-avatar"
                      @error="handleAvatarError"
                  />
                  <div class="comment-info">
                    <div class="comment-header">
                      <span class="username">{{ getUserName(comment) }}</span>
                      <span class="time">{{ formatDate(comment.createdAt) }}</span>
                    </div>
                    <p v-if="comment.comment" class="comment-text">{{ comment.comment }}</p>
                    <p v-else class="comment-text no-comment">该用户没有填写评论</p>
                    <div v-if="isOwnComment(comment)" class="comment-actions">
                      <span @click="deleteComment(comment.id)">删除</span>
                    </div>
                  </div>
                </div>
                <el-empty
                    v-if="reviews.length === 0"
                    class="no-comments"
                    description="暂无评论，快来发表第一条评论吧~"
                ></el-empty>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 图片预览弹窗 -->
      <el-dialog
          v-model="showImageViewer"
          :close-on-click-modal="true"
          :modal="true"
          :width="imageViewerWidth"
          title="图片预览"
      >
        <img
            :alt="product.name || '商品图片'"
            :src="currentImageUrl"
            class="preview-image"
            @error="e => e.target.src = 'https://picsum.photos/800/400'"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import {computed, onActivated, onMounted, ref} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import http from "@/request/Http.js";
import {
  ElButton,
  ElCarousel,
  ElCarouselItem,
  ElDialog,
  ElEmpty,
  ElInput,
  ElMessage,
  ElSkeleton,
  ElTabPane,
  ElTabs
} from 'element-plus'

const route = useRoute()
const router = useRouter()
const productId = route.params.id

// 核心状态
const loading = ref(true)
const product = ref({})
const activeTab = ref('detail')
const commentInput = ref('')

// 评论相关状态
const reviews = ref([])

// 点赞/关注/收藏状态
const isLiked = ref(false)
const likeCount = ref(0)
const isFollowed = ref(false)
const sellerId = ref(null)
const isFavorite = ref(false)

// 登录状态
const isLogin = computed(() => !!sessionStorage.getItem('token'))

// 图片预览相关状态
const showImageViewer = ref(false)
const currentImageUrl = ref('')
const imageViewerWidth = ref('80%')

// 页面初始化
onMounted(async () => {
  try {
    await fetchProductDetail();
    await Promise.all([
      checkFollowStatus(),
      checkFavoriteStatus(),
      fetchReviews(),
      increaseViewCount()
    ]);
  } catch (error) {
    console.error('页面初始化失败:', error);
    ElMessage.error('页面加载失败，请刷新重试');
  } finally {
    loading.value = false;
  }
});

// 页面激活时重新校验状态
onActivated(async () => {
  if (sellerId.value && isLogin.value) {
    await checkFollowStatus();
  }
  if (productId) {
    await fetchReviews();
  }
});

// 立即购买功能
const handleBuyNow = async () => {
  if (!isLogin.value) {
    ElMessage.warning('请登录后购买')
    await router.push('/login')
    return
  }

  try {
    const orderData = {
      productId: productId,
      totalAmount: product.value.price
    }
    const response = await http.post('/order/create', orderData)
    if (response.code === 200) {
      ElMessage.success('订单创建成功')
      await router.push({
        name: 'OrderDetail',
        params: {id: response.data.id},
        query: {role: 'buyer'}
      })
    } else {
      ElMessage.error(response.msg || '创建订单失败')
    }
  } catch (error) {
    console.error('创建订单失败:', error)
    ElMessage.error('创建订单失败，请重试')
  }
}

// 加入购物车功能
const handleAddToCart = async () => {
  if (!isLogin.value) {
    ElMessage.warning('请登录后操作')
    await router.push('/login')
    return
  }
  try {
    const cartData = {productId: productId,}
    const response = await http.post('/cart/add', cartData)
    if (response.code === 200) {
      ElMessage.success('已加入购物车')
    } else {
      ElMessage.error(response.msg || '加入购物车失败')
    }
  } catch (error) {
    console.error('加入购物车失败:', error)
    ElMessage.error('加入购物车失败')
  }
}

// 获取商品详情
const fetchProductDetail = async () => {
  try {
    const response = await http.get(`/product/getGoodForEdit/${productId}`);
    if (response.code === 200) {
      product.value = response.data;
      sellerId.value = product.value.sellerId || product.value.seller?.id || null;
      likeCount.value = product.value.likeCount || 0;
      const likedGoods = JSON.parse(localStorage.getItem('likedGoods') || '[]');
      isLiked.value = likedGoods.includes(productId);
    } else {
      ElMessage.error(response.msg || '获取商品详情失败');
    }
  } catch (error) {
    console.error('获取商品详情出错:', error);
    ElMessage.error('获取商品详情失败');
  }
};

// 点赞功能
const handleLike = () => {
  if (!isLogin.value) {
    ElMessage.warning('请登录后点赞')
    router.push('/login')
    return
  }
  isLiked.value = !isLiked.value
  likeCount.value += isLiked.value ? 1 : -1
  const likedGoods = JSON.parse(localStorage.getItem('likedGoods') || '[]')
  isLiked.value ?
      (!likedGoods.includes(productId) && likedGoods.push(productId)) :
      likedGoods.splice(likedGoods.indexOf(productId), 1)
  localStorage.setItem('likedGoods', JSON.stringify(likedGoods))
  ElMessage.success(isLiked.value ? '点赞成功' : '取消点赞成功')
}

// 检查关注状态
const checkFollowStatus = async () => {
  const currentSellerId = sellerId.value || product.value.sellerId || product.value.seller?.id;
  isFollowed.value = false;

  if (!isLogin.value) {
    console.warn('检查关注状态：用户未登录');
    return;
  }
  if (!currentSellerId) {
    console.warn('检查关注状态：未获取到卖家ID');
    ElMessage.warning('无法获取卖家信息，无法判断关注状态');
    return;
  }

  try {
    const response = await http.get(`/FollowAndFavorite/checkFollow?sellerId=${currentSellerId}`);
    if (response.code === 200) {
      isFollowed.value = response.data;
    } else {
      console.error('检查关注状态失败：', response.msg);
      ElMessage.warning('获取关注状态失败，默认显示未关注');
      isFollowed.value = false;
    }
  } catch (error) {
    console.error('检查关注状态接口异常：', error);
    ElMessage.error('网络错误，无法获取关注状态');
    isFollowed.value = false;
  }
}

// 处理关注/取消关注
const handleFollowSeller = async () => {
  const currentSellerId = sellerId.value || product.value.sellerId || product.value.seller?.id;

  if (!isLogin.value) {
    ElMessage.warning('请登录后关注卖家');
    await router.push('/login');
    return;
  }
  if (!currentSellerId) {
    ElMessage.error('无法获取卖家信息');
    return;
  }

  try {
    const checkResp = await http.get(`/FollowAndFavorite/checkFollow?sellerId=${currentSellerId}`);
    if (checkResp.code !== 200) {
      ElMessage.error('获取当前关注状态失败，请重试');
      return;
    }
    const realFollowStatus = checkResp.data;

    if (realFollowStatus) {
      const delResp = await http.post('/FollowAndFavorite/deleteFollow', [currentSellerId]);
      if (delResp.code === 200) {
        isFollowed.value = false;
        ElMessage.success('取消关注成功');
      } else {
        ElMessage.error(delResp.msg || '取消关注失败');
      }
    } else {
      const addResp = await http.post('/FollowAndFavorite/addFollow', {sellerId: currentSellerId});
      if (addResp.code === 200) {
        isFollowed.value = true;
        ElMessage.success('关注卖家成功');
      } else {
        ElMessage.error(addResp.msg || '关注卖家失败');
      }
    }
  } catch (error) {
    console.error('处理关注失败:', error);
    ElMessage.error(isFollowed.value ? '取消关注失败' : '关注卖家失败');
  }
}

// 收藏功能
const checkFavoriteStatus = async () => {
  if (!isLogin.value) {
    isFavorite.value = false;
    return;
  }
  try {
    const response = await http.get(`/FollowAndFavorite/checkFavorite?productId=${productId}`);
    isFavorite.value = response.code === 200 ? response.data : false;
    if (product.value) {
      const countResp = await http.get(`/FollowAndFavorite/getFavoriteCount?productId=${productId}`);
      if (countResp.code === 200) {
        product.value.favoriteCount = countResp.data;
      }
    }
  } catch (error) {
    console.error('检查收藏状态失败:', error);
    isFavorite.value = false;
  }
}

const handleFavorite = async () => {
  if (!isLogin.value) {
    ElMessage.warning('请登录后收藏')
    await router.push('/login')
    return
  }

  try {
    if (isFavorite.value) {
      const response = await http.post('/FollowAndFavorite/deleteFavorite', [productId])
      if (response.code === 200) {
        isFavorite.value = false
        product.value.favoriteCount = Math.max(0, (product.value.favoriteCount || 0) - 1)
        ElMessage.success('取消收藏成功')
        setRefreshFlag()
      } else {
        ElMessage.error(response.msg || '取消收藏失败')
      }
    } else {
      const response = await http.post('/FollowAndFavorite/addFavorite', {productId})
      if (response.code === 200) {
        isFavorite.value = true
        product.value.favoriteCount = (product.value.favoriteCount || 0) + 1
        ElMessage.success('收藏成功')
        setRefreshFlag()
      } else {
        ElMessage.error(response.msg || '收藏失败')
      }
    }
  } catch (error) {
    console.error('处理收藏失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

// 设置刷新标记
const setRefreshFlag = () => {
  router.beforeEach((to, from, next) => {
    if (from.path === `/userHome/showGood/${productId}` && to.path === '/userHome/showGoodList') {
      to.meta.needRefresh = true;
    }
    next();
  });
}

// 评论功能
const submitComment = async () => {
  if (!isLogin.value) {
    ElMessage.warning('请登录后发表评论')
    await router.push('/login')
    return
  }
  try {
    const comment = {
      productId,
      userId: localStorage.getItem('userId') || '',
      comment: commentInput.value.trim(),
      rating: 5
    }
    const response = await http.post('/review/addReview', comment)
    if (response.code === 200) {
      ElMessage.success('评论成功')
      commentInput.value = ''
      // 重新获取评论列表
      await fetchReviews()
    } else {
      ElMessage.error(response.msg || '评论失败')
    }
  } catch (error) {
    console.error('提交评论失败:', error)
    ElMessage.error('评论失败')
  }
}

// 删除评论
const deleteComment = async (commentId) => {
  if (!isLogin.value) {
    ElMessage.warning('请登录后删除评论')
    await router.push('/login')
    return
  }
  try {
    const response = await http.post(`/review/deleteReview?id=${commentId}`)
    if (response.code === 200) {
      ElMessage.success('删除评论成功')
      // 重新获取评论列表
      await fetchReviews()
    } else {
      ElMessage.error(response.msg || '删除评论失败')
    }
  } catch (error) {
    console.error('删除评论失败:', error)
    ElMessage.error('删除评论失败')
  }
}

// 增加浏览量
const increaseViewCount = async () => {
  try {
    await http.post(`/product/increaseViewCount/${productId}`)
  } catch (error) {
    console.error('增加浏览量失败:', error)
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString()
}

// 判断是否是自己的评论
const isOwnComment = (comment) => {
  return isLogin.value && comment.userId === localStorage.getItem('userId')
}

// 跳转到聊天页面
const goToChat = () => {
  if (!isLogin.value) {
    ElMessage.warning('请登录后聊天')
    router.push('/login')
    return
  }
  router.push({
    name: 'Chat',
    params: {
      sellerId: sellerId.value || product.value.sellerId || product.value.seller?.id
    }
  })
}

// 获取用户头像
const getUserAvatar = (comment) => {
  return comment.user?.avatar || comment.avatar || 'https://picsum.photos/100/100'
}

// 头像加载失败处理
const handleAvatarError = (event) => {
  event.target.src = 'https://picsum.photos/100/100'
}

// 获取用户名
const getUserName = (comment) => {
  return comment.user?.username ||
      comment.user?.realname ||
      comment.username ||
      comment.realname ||
      '匿名用户'
}

// 获取评论列表
const fetchReviews = async () => {
  try {
    const response = await http.get(`/review/getReviewList?productId=${productId}`)
    if (response.code === 200) {
      reviews.value = response.data || []
    } else {
      console.error('获取评论失败:', response.msg)
    }
  } catch (error) {
    console.error('获取评论失败:', error)
  }
}

// 图片点击放大处理
const handleImageClick = (imageUrl) => {
  currentImageUrl.value = imageUrl
  showImageViewer.value = true
}
</script>

<style scoped>
/* 样式部分保持不变 */
.goods-detail-page {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.goods-skeleton {
  padding: 20px;
}

.skeleton-image {
  width: 100%;
  height: 400px;
  background: #f2f3f5;
  border-radius: 4px;
  margin-bottom: 20px;
}

.skeleton-title {
  width: 70%;
  height: 30px;
  background: #f2f3f5;
  border-radius: 4px;
  margin-bottom: 15px;
}

.skeleton-stats {
  width: 40%;
  height: 20px;
  background: #f2f3f5;
  border-radius: 4px;
  margin-bottom: 15px;
}

.skeleton-price {
  width: 30%;
  height: 36px;
  background: #f2f3f5;
  border-radius: 4px;
  margin-bottom: 20px;
}

.skeleton-meta {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 20px;
}

.skeleton-meta > div {
  height: 20px;
  background: #f2f3f5;
  border-radius: 4px;
}

.skeleton-actions {
  width: 60%;
  height: 40px;
  background: #f2f3f5;
  border-radius: 4px;
}

.image-container {
  width: 100%;
  margin-bottom: 20px;
  border: 1px solid #eee;
  padding: 10px;
  border-radius: 4px;
}
.main-image {
  width: 100%;
  height: auto;
  display: block;
  object-fit: contain;
}

.info-container {
  width: 100%;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 20px;
}

.goods-title {
  font-size: 22px;
  margin-bottom: 15px;
  line-height: 1.5;
  color: #333;
}

.stats {
  color: #888;
  font-size: 14px;
  margin-bottom: 15px;
  display: flex;
  gap: 20px;
}

.price-box {
  margin-bottom: 20px;
}

.price {
  font-size: 26px;
  color: #ff4500;
  font-weight: bold;
}

.meta-info {
  margin-bottom: 20px;
  line-height: 1.8;
  color: #666;
}

.seller-info {
  display: flex;
  align-items: center;
}

.action-buttons {
  display: flex;
  gap: 15px;
  margin-top: 20px;
}

:deep(.el-button.favorited-btn) {
  color: #ff4500 !important;
  border-color: #ff4500 !important;
}

:deep(.el-button.liked-btn) {
  color: #1890ff !important;
  border-color: #1890ff !important;
}

:deep(.el-button.followed-btn) {
  color: #ff4500 !important;
}

:deep(.el-button.follow-btn) {
  color: #409eff !important;
}
.buy-button {
  background: #ff4400 !important;
  border-color: #ff4400 !important;
  color: #fff !important;
  padding: 8px 16px !important;
  border-radius: 20px !important;
  font-size: 14px !important;
  font-weight: 500 !important;
  transition: all 0.2s ease !important;
}

.buy-button:hover {
  background: #ff5722 !important;
  border-color: #ff5722 !important;
}

.tabs-container {
  width: 100%;
  border: 1px solid #eee;
  border-radius: 4px;
  overflow: hidden;
}
.detail-content {
  padding: 20px;
  width: 100%;
}

.detail-text {
  line-height: 1.8;
  color: #333;
  margin-bottom: 20px;
}

.images-container-full {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-top: 10px;
}

.detail-image-item {
  width: 100%;
  max-width: 800px;
  max-height: 400px;
  height: auto;
  object-fit: contain;
  border-radius: 4px;
  margin: 0 auto;
  min-height: 200px;
  min-width: 300px;
}

.detail-images-list {
  margin-top: 30px;
}

.detail-images-title {
  font-size: 18px;
  color: #333;
  margin-bottom: 15px;
  border-bottom: 1px solid #eee;
  padding-bottom: 8px;
}

.no-detail-placeholder {
  text-align: center;
  padding: 30px 0;
}

.no-detail-title {
  font-size: 16px;
  color: #666;
  margin-bottom: 20px;
}

.no-detail-empty {
  margin: 50px 0;
}

.comment-content {
  padding: 20px;
}

.comment-input {
  width: 100%;
  margin-bottom: 10px;
}

.submit-comment {
  float: right;
}

.comments-list {
  margin-top: 40px;
}

.comment-item {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #f5f5f5;
  object-fit: cover;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.username {
  font-weight: bold;
  color: #333;
}

.time {
  color: #999;
  font-size: 12px;
}

.comment-text {
  margin-bottom: 5px;
  color: #666;
  line-height: 1.6;
}

.comment-actions {
  color: #666;
  font-size: 12px;
}

.comment-actions span {
  cursor: pointer;
  color: #ff4500;
}

.no-comments {
  padding: 40px 0;
  text-align: center;
}

.no-comment {
  color: #999;
  font-style: italic;
}

:deep(.el-empty__description) {
  margin-top: 10px;
}

.image-container {
  width: 100%;
  overflow: hidden; /* 防止图片溢出容器 */
}

.main-image {
  width: 100%; /* 图片宽度充满容器 */
  height: 100%; /* 图片高度充满轮播容器 */
  object-fit: contain; /* 保持图片比例，完整显示在容器内（不会裁剪） */
  object-position: center; /* 图片居中显示 */
}

/* 图片预览样式 */
.preview-image {
  width: 100%;
  height: auto;
  max-height: 80vh;
  object-fit: contain;
}

/* 为可点击图片添加鼠标悬停效果 */
.main-image, .detail-image-item {
  cursor: zoom-in;
  transition: transform 0.2s ease;
}

.main-image:hover, .detail-image-item:hover {
  transform: scale(1.02);
}
</style>